<template>
  <div class="cert-page-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.params.title"
        placeholder="搜索证书名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        class="filter-item"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加证书
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        label="证书ID"
        prop="id"
        align="center"
        width="180"
      />
      <el-table-column
        label="证书名称"
        min-width="150px"
      >
        <template slot-scope="{row}">
          <router-link
            :to="{ name: 'UpdateCert', params:{id: row.id}}"
            class="link-type"
          >
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="证书编号"
        align="center"
        prop="code"
        width="150"
      />
      <el-table-column
        label="证书备注"
        align="center"
        prop="remark"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="操作"
        align="center"
        width="250"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            @click="handleRelateExam(row)"
          >
            已关联考试
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <!-- 关联考试对话框 -->
    <el-dialog
      title="已关联考试"
      :visible.sync="dialogRelateExamVisible"
      width="900px"
      top="8vh"
    >
      <div style="margin-bottom: 20px;">
        <span style="font-weight: bold; color: #606266;">证书名称：</span>
        <span style="color: #303133;">{{ currentCert ? currentCert.title : '' }}</span>
      </div>

      <div v-if="relatedExams.length > 0">
        <el-table
          :data="relatedExams"
          border
          style="width: 100%"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
        >
          <el-table-column prop="title" label="考试名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="startTime" label="开始时间" width="160" align="center">
            <template slot-scope="{row}">
              <span v-if="row.startTime">{{ new Date(row.startTime).toLocaleDateString() }}</span>
              <span v-else style="color: #c0c4cc;">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="160" align="center">
            <template slot-scope="{row}">
              <span v-if="row.endTime">{{ new Date(row.endTime).toLocaleDateString() }}</span>
              <span v-else style="color: #c0c4cc;">-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="empty-state">
        <i class="el-icon-document" style="font-size: 48px; color: #c0c4cc;"></i>
        <p style="margin: 16px 0 0 0; color: #909399; font-size: 14px;">暂无关联考试</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRelateExamVisible = false" size="medium">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.empty-state {
  text-align: center;
  padding: 40px 20px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px dashed #d9d9d9;
}

.dialog-footer {
  text-align: center;
}
</style>

<script>
import { fetchPaging, getExamsByCertId } from '@/api/cert/cert'
import { fetchList as fetchUserList } from '@/api/sys/user/user.js'
import { post } from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'CertManagement',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        params: {
          title: ''
        }
      },
      dialogRelateExamVisible: false,
      dialogIssueVisible: false,
      currentCert: null,
      issueForm: {
        userId: '',
        examId: '',
        certId: ''
      },
      userList: [],
      relatedExams: [],
      issueLoading: false,
      issueRules: {
        userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
        examId: [{ required: true, message: '请选择考试', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchPaging(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ name: 'AddCert' })
    },
    handleDelete(row) {
      this.$confirm('确认删除该证书吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        post('/exam/api/cert/delete', { ids: [row.id] }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
        // 取消删除
      })
    },
    handleRelateExam(row) {
      this.currentCert = row
      this.dialogRelateExamVisible = true

      // 加载已关联的考试
      this.loadRelatedExams(row.id)
    },
    loadRelatedExams(certId) {
      getExamsByCertId(certId).then(response => {
        if (response.code === 0 && response.data) {
          this.relatedExams = response.data
        } else {
          this.relatedExams = []
        }
      }).catch(() => {
        this.relatedExams = []
      })
    },
    handleManualIssue(row) {
      this.currentCert = row
      this.dialogIssueVisible = true
      this.issueForm = {
        userId: '',
        examId: '',
        certId: row.id
      }

      // 加载用户列表
      this.loadUserList()

      // 加载关联的考试
      this.loadRelatedExamsForIssue(row.id)
    },
    loadUserList() {
      fetchUserList({}).then(response => {
        this.userList = response.data.records || response.data || []
      })
    },
    loadRelatedExamsForIssue(certId) {
      getExamsByCertId(certId).then(response => {
        if (response.code === 0 && response.data) {
          this.relatedExams = response.data
        }
      })
    }
  }
}
</script>

<style scoped>
.cert-page-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
.link-type {
  color: #409EFF;
  text-decoration: none;
}
</style>
